package com.pj.wisdomlogistics.ui.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.activity.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.zackratos.ultimatebar.UltimateBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;


public abstract class BaseFragment extends Fragment {
    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";
    protected View rootView;
    private BaseActivity mActivity;
    private boolean isFirstResume = true;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;
    private boolean isPrepared;
    public UltimateBar ultimateBar;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //解决内存重启add的重叠问题
        if (savedInstanceState != null) {
            boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            if (isSupportHidden) {
                fragmentTransaction.hide(this);
            }
            else{
                fragmentTransaction.show(this);
            }
        }

        ultimateBar = new UltimateBar(mActivity);

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(STATE_SAVE_IS_HIDDEN,isHidden());
        super.onSaveInstanceState(outState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(getContentView(), container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivity = (BaseActivity) getActivity();
        if (isApplyButterKnife()) ButterKnife.bind(this, view);
        if (isApplyEventBus()) EventBus.getDefault().register(this);
        initView();
        initData();

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.e("tag", "onActivityCreated");
        initPrepare();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (getUserVisibleHint()) {
            onUserVisible();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getUserVisibleHint()) {
            onUserInvisible();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e("tag", "setUserVisibleHint:" +isVisibleToUser);
        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false;
                Log.e("tag", "basefragment true isVisibleToUser=" + isVisibleToUser);
                initPrepare();
            } else {
                onUserVisible();
            }
        } else {
            if (isFirstInvisible) {
                isFirstInvisible = false;
                onFirstUserInvisible();
            } else {
                onUserInvisible();
            }
        }
    }

    private synchronized void initPrepare() {
        Log.e("tag", "basefragment initPrepare...");
        if (isPrepared) {
            Log.e("tag", "basefragment onFirstUserVisible...");
            onFirstUserVisible();
        } else {
            isPrepared = true;
        }
    }



    protected abstract void initView();

    protected abstract void initData();

    protected abstract void onFirstUserVisible();

    /**
     * this method like the fragment's lifecycle method onResume()
     */
    protected abstract void onUserVisible();

    /**
     * when fragment is invisible for the first time
     */
    private void onFirstUserInvisible() {
        // here we do not recommend do something
    }

    /**
     * this method like the fragment's lifecycle method onPause()
     */
    protected abstract void onUserInvisible();


    @Override
    public void onDestroyView() {
        if (isApplyEventBus()) EventBus.getDefault().unregister(this);
        super.onDestroyView();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCenter eventCenter) {
        if (eventCenter != null) {
            onEventCome(eventCenter);
        }
    }


    public abstract int getContentView();

    protected abstract boolean isApplyEventBus();

    protected abstract boolean isApplyButterKnife();

    protected abstract void onEventCome(EventCenter eventCenter);

    public void startActivity(Class cls){
        Intent intent = new Intent(getContext(),cls);
        startActivity(intent);

    }

    /**
     * 检查是否有某项权限
     * @param permission
     * @return
     */
    public boolean checkPermission(String permission){
        if (ContextCompat.checkSelfPermission(getContext(),permission)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }

    /**
     * 检查是否有某项权限
     * @param permissions
     * @return
     */
    public boolean checkPermissions(String[] permissions){
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getContext(),permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检查是缺少的权限
     * @param permissions
     * @return
     */
    public String[] checkLackPermissions(String[] permissions){
        List<String> lackPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (!checkPermission(permission)) {
                lackPermissions.add(permission);
            }
        }
        String[] lackPermissionArray=null;
        if (lackPermissions.size()>0) {
            lackPermissionArray = new String[lackPermissions.size()];
            lackPermissions.toArray(lackPermissionArray);
        }

        return  lackPermissionArray;
    }

    public void requestSystemPermissions(String[] permissions,int requestCode){

        requestPermissions(permissions,requestCode);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if (mRequestPermission != null){
            mRequestPermission.onRequestResult(requestCode,permissions,grantResults);
        }
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }

    private BaseActivity.RequestPermission mRequestPermission;
    public void setRequestPermissionListener(BaseActivity.RequestPermission requestPermission){
        mRequestPermission = requestPermission;
    }

    public void showProgressDialog() {

        mActivity.showProgressDialog();
    }

   /* public void showProgressDialog(String message) {
        return mActivity.showProgressDialog(message);
    }*/

    public void dismissProgressDialog() {
        mActivity.dismissProgressDialog();
    }
}
